package com.example.springbootdemo.controller;

import com.example.springbootdemo.entity.User;
import com.example.springbootdemo.service.Userservice;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import java.util.List;

@Controller
public class UserController {
   @Resource
   private Userservice userservice;

   @RequestMapping("userList")
    public String getUser(Model model){
       try {
           List<User> userList = userservice.userList();
           model.addAttribute("userList",userList);
       }catch(Exception e){
           e.printStackTrace();
       }
        return  "index";
    }

    @RequestMapping("delUser")
    public Object del(Integer id,Model model) throws Exception {
       boolean delete = userservice.delete(id);
       if(delete){
           return "redirect:/userList";
       }
       return "index";
    }

    @RequestMapping("getUserId")
    public String getUserId(Integer id,Model model) throws Exception{
       User user = userservice.getUser(id);
       model.addAttribute("user",user);
       return "update";
    }

    @RequestMapping("/update")
    public String update(User user,Model model) throws Exception{
       boolean updateuser = userservice.update(user);
       if (updateuser){
           return "redirect:/userList";
       }
       return "update";
    }

    @RequestMapping("add")
    public String insert(User user,Model model) throws Exception{
       boolean insert = userservice.insert(user);
       if (insert){
           return "redirect:/userList";
       }
       return "add";
    }
}
